package org.protege.owl.examples.tab;

//import java.io.StringWriter;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.log4j.Logger;
import org.protege.editor.owl.ui.view.AbstractOWLViewComponent;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.TransferHandler;

import org.protege.editor.owl.model.OWLModelManager;
//import org.protege.owl.example.Metrics;
import org.protege.owl.examples.tab.grammar.FOLAnalyzer;

public class ExampleViewComponent extends AbstractOWLViewComponent {
    private static final long serialVersionUID = -4515710047558710080L;

    @Override
    protected void disposeOWLView() {
        //metricsComponent.dispose();
    }

    @Override
    protected void initialiseOWLView() throws Exception
    {
    	initGUI();
    	initListeners();
    	
        modelManager = super.getOWLModelManager();
        predicateRegistry = new PredicateRegistry(modelManager);
        variableRegistry = new VariableRegistry();
        predicateRegistry.setVariableRegistry(variableRegistry);
        folAnalyzer = new FOLAnalyzer();
        folAnalyzer.setEnvironment(predicateRegistry, variableRegistry);

        log.info("Follow View Initialized");
    }
    
    private void initListeners()
    {
    	// Init query button listener
    	queryButton.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent ev)
			{
				try
				{
					// Query text evaluation
					String queryText = queryArea.getText();
					if ((queryText!=null)&&(queryText.compareTo("")!=0))
					{
						folAnalyzer.query(queryText);
						ResultTable resultTable = folAnalyzer.getResultTable();
						if (resultTable != null) publishResultTable(resultTable);
					}
				}
				catch(Exception ex)
				{
					ErrorLogger.log(ex);
				}
			}});
    	
    	copyButton.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0)
			{
				TransferHandler th = resultViewTable.getTransferHandler();
				if (th != null)
				{
					Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
					th.exportToClipboard(resultViewTable, cb, TransferHandler.COPY);
				}
				
			}});
    }
    
    private void initGUI()
    {
    	// Layout
    	setLayout(new BorderLayout());
    	
    	// Query button
    	queryButton.setMinimumSize(new Dimension(30,30));
        queryButton.setMaximumSize(new Dimension(30,30));
        queryButton.setPreferredSize(new Dimension(30,30));
        
        // Query area
        queryPane.setMinimumSize(new Dimension(150,150));
        queryPane.setPreferredSize(new Dimension(150,150));
        queryArea.setCaretColor(new Color(255,255,255));
        queryArea.setBackground(new Color(0,40,130));
        queryArea.setForeground(new Color(255,255,255));
        
        // Result area
        resultPane.setMinimumSize(new Dimension(150,150));
        resultPane.setPreferredSize(new Dimension(150,150));
        
        // Add buttons to panel
        buttonPanel.setLayout(new GridLayout());
        buttonPanel.add(queryButton);
        buttonPanel.add(copyButton);
        
        // Add elements to layout
        add(queryPane, BorderLayout.PAGE_START);
        add(resultPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.PAGE_END);
    }
    
    private void publishResultTable(ResultTable rt)
    {
    	ArrayList<String> columns = new ArrayList<String>();
    	int rowNum = 0;
    	try
    	{
    		rowNum = rt.size();
    	}
    	catch(Exception e)
    	{
    		e.printStackTrace();
    		ErrorLogger.log(e);
    	}
    	Iterator<Variable> iter = rt.getVarialbeSet().iterator();
    	while(iter.hasNext())
    	{
    		Variable var = iter.next();
    		columns.add(var.name());
    	}
    	resultViewTable.setModel(new PublisherTableModel(columns,rowNum));
    	
    	iter = rt.getVarialbeSet().iterator();
    	int iterIndex = 0;
    	while(iter.hasNext())
    	{
    		Variable var = iter.next();
    		for (int index=0;index<rowNum;index++)
    		{
    			String instanceString = rt.getInstance(var, index);
    			resultViewTable.getModel().setValueAt(instanceString, index, iterIndex);
    		}
    		iterIndex++;
    	}
    }
    
    // Logger for FOLLOW Example View Component
    private static final Logger log = Logger.getLogger(ExampleViewComponent.class);
    
    // Owl model manager
    private static OWLModelManager modelManager ;
    // The predicate registry
    private static PredicateRegistry predicateRegistry;
    // The variable registry
    private static VariableRegistry variableRegistry;
    // Sample result tables
    private static ResultTable rt1, rt2;
    
    // Result view table
    private JTable resultViewTable = new JTable(new PublisherTableModel());
    
    // JPanel for buttons
    private JPanel buttonPanel = new JPanel();    
    // Query button
    private JButton queryButton = new JButton("QUERY ONTOLOGY");
    // Copy button
    private JButton copyButton = new JButton("COPY RESULTS");

    // Query text area
    private JTextArea queryArea = new JTextArea();
    // Query scroll pane for scrolling enablement
    private JScrollPane queryPane = new JScrollPane(queryArea);
    // Result scroll pane
    private JScrollPane resultPane = new JScrollPane(resultViewTable);
    
    // FOL analyzer for Follow
    private FOLAnalyzer folAnalyzer;
}
